import {Api_url} from './config'
import Vue from 'vue'
import http from './axios.js'
import UserModel from '../model/user.js'

class XcxToken {
	constructor() {
		this.tokenUrl = Api_url + 'user/get_xcx_token';
		this.getInfo = Api_url + 'user/info';
	}
	
	//初始化登陆
	async verify() {  
		console.log("小程序获取token")
		console.log('开始获取token')
		var that = this;
		var token = uni.getStorageSync('token'); //获取缓存
		if (!token) {
			//向微信api拿code，再向tp的api拿token
			await this.getTokenFromServer();
		} else {
			await this._veirfyFromServer(); //验证token是否过期，过期调用.getTokenFromServer函数获取
		}
	}
	
	async getTokenFromServer() {
		var that = this;
		console.log('get_token')
		await uni.login({
			provider: 'weixin',
			success: function(res) {
				uni.request({
					url: that.tokenUrl,
					method: 'POST',
					data: {
						code: res.code
					},
					success: function(res) {
						if(res.data.code!=200){
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
							return;
						}
						
						uni.setStorageSync('token', res.data.data.token);
						that._getinfo()
					}
				})
			}
		})
	}
	
	async _getinfo()
	{
		UserModel.get_infor().then(res=>{
			if(res.code==200){
				uni.setStorageSync('infor', res.data);
				let invite_id=uni.getStorageSync('invite_id')
				if(invite_id){
					UserModel.bind_user(invite_id).then(res=>{
						
					})
				}
			}
		})
	}
	
	//验证token
	async _veirfyFromServer() {
		var that = this
		UserModel.token_verify().then(res=>{
			if(res.data==true){
				that._getinfo()
			}else{
				that.getTokenFromServer();
			}
		})
	}
}

export {
	XcxToken
};
